package com.qijian.sync;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.qijian.common.utils.StringUtils;
import com.qijian.common.utils.sync.KingDeeCommon;
import com.qijian.common.utils.sync.enums.ObjectTypeEnum;
import com.qijian.system.domain.SysConfig;
import com.qijian.maindata.service.IExchangeRateService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @author gw
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class BaseKingDee extends BaseKingDeeSync {

    private final KingDeeCommon kingDeeCommon;
    private final IExchangeRateService exchangeRateService;


    @Transactional(rollbackFor = Exception.class)
    public void removeData() {
        final String configKey = "sync.deleteData";
        SysConfig config = configService.selectConfigByKeyVal(configKey);
        String conditions = null;
        AtomicReference<Date> maxTime = new AtomicReference<>();
        Date configVal;
        if (StringUtils.isNotBlank(config.getConfigValue())) {
            configVal = Convert.toDate(config.getConfigValue());
            maxTime.set(configVal);
            conditions = "FDATETIME > '" + config.getConfigValue() + "'";
        }

        List<String> kingdeeType = Arrays.stream(ObjectTypeEnum.values()).map(Enum::name).collect(Collectors.toList());

        Map<String, List<String>> deleteMap = kingDeeCommon.existData(conditions, kingdeeType);


        deleteMap.forEach(this::deleteByType);

        config.setConfigValue(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
        configService.updateConfig(config);
    }

    private void deleteByType(String type, List<String> ids) {
        if (StrUtil.isBlank(type) || CollectionUtil.isEmpty(ids)) {
            return;
        }
        ObjectTypeEnum objectTypeEnum = ObjectTypeEnum.valueOf(type);
        log.info("删除（{}）内码：{}", objectTypeEnum.name(), ids);
        switch (objectTypeEnum) {


            case BD_Rate: {
                exchangeRateService.removeByIds(ids);
                break;
            }


            default:
                break;
        }
    }
}
